package com.zj.httpdemo.http.get;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Lenovo on 2017/5/13.
 */

public class BitmapTask extends AsyncTask<String, Void, Bitmap> {
    private static final String TAG = BitmapTask.class.getSimpleName();

    @Override
    protected Bitmap doInBackground(String... params) {
        Log.e(TAG, "doInBackground: url = " + params[0]);

        HttpsURLConnection connection = null;
        InputStream in = null;
        BufferedInputStream bis = null;

        Bitmap bitmap = null;
        try {
            URL url = new URL(params[0]);

            connection = (HttpsURLConnection) url.openConnection();
            // Timeout for reading InputStream arbitrarily set to 3000ms.
            connection.setReadTimeout(3000);
            // Timeout for connection.connect() arbitrarily set to 3000ms.
            connection.setConnectTimeout(3000);
            // For this use case, set HTTP method to GET.
            connection.setRequestMethod("GET");
            // Already true by default but setting just in case; needs to be true since this request
            // is carrying an input (response) body.
            connection.setDoInput(true);

            // Open communications link (network traffic occurs here).
            connection.connect();

            Log.e(TAG, "doInBackground: response code = " + connection.getResponseCode());
            if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                in = connection.getInputStream();
                bis = new BufferedInputStream(in);

                bitmap = BitmapFactory.decodeStream(bis);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
            try {
                if (in != null) {
                    in.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Log.e(TAG, "doInBackground: end");
        return bitmap;
    }
}
